package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xrit.sunnyday.dao.SetmealDao;
import com.xrit.sunnyday.entity.PageResult;
import com.xrit.sunnyday.entity.QueryPageBean;
import com.xrit.sunnyday.exception.SunnydayException;
import com.xrit.sunnyday.pojo.Setmeal;
import com.xrit.sunnyday.service.SetmealService;
import com.xrit.sunnyday.utils.QiNiuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
public class SetMealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    /**
     * 添加套餐以及关联的检查组
     */
    @Override
    @Transactional
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //1.添加套餐
        setmealDao.add(setmeal);
        //2.获取套餐的id
        Integer setmealId = setmeal.getId();
        //3.添加套餐与检查组的关系
        if(null != checkgroupIds){
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addSetmealCheckGroup(setmealId, checkgroupId);
            }
        }
        //第二部分：FreeMark
        //新增生成静态页面
        generateMobileStaticHtml();
    }

    private void generateMobileStaticHtml() {
        try{
            //1.生成套餐列表的静态页面
            generateSetmealListHtml();
            //2.生成具体套餐对应的套餐响应静态页面
            generateSetmealDetailHtml();
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }
    /**
     * 生成套餐列表的静态页面
     */
    private void generateSetmealListHtml() {
        //1.准备模板文件
        String templateFileName = "mobile_setmeal.ftl";
        //2.准备套餐列表需要的数据
        List<Setmeal> setmealList = setmealDao.findAll();
        //2.1拼图片路径
        setmealList.forEach(setmeal -> {
            setmeal.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());
        });
        //2.3构造数据
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("setmealList",setmealList);
        //3.输出路径
        String setmealListFile = out_put_path+"mobile_setmeal.html";
        //4.调用静态页面生成
        generateHtml(templateFileName,dataMap,setmealListFile);
    }
    /**
     * 生成具体套餐对应的套餐相应静态页面
     */
    private void generateSetmealDetailHtml() {
        //1.准备模板文件
        String templateFileName = "mobile_setmeal_detail.ftl";
        //2.准备套餐列表需要的数据
        List<Setmeal> setmealList = setmealDao.findAll();
        for(Setmeal setmeal:setmealList){
            //根据页面静态传参的id查询套餐对应的详情
            Setmeal setmeal1Detail = setmealDao.findDetailById(setmeal.getId());
            //设置图片路径
            setmeal1Detail.setImg(QiNiuUtils.DOMAIN+setmeal1Detail.getImg());
            //构造数据
            Map<String,Object> dataMap = new HashMap<String,Object>();
            dataMap.put("setmeal",setmeal1Detail);
            //输出路径
            String setmealListFile = out_put_path+"mobile_setmeal_"+setmeal1Detail.getId()+".html";
            //调用工具方法生成静态页面
            generateHtml(templateFileName,dataMap,setmealListFile);
        }


    }

    /**
     * 分页查询
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //1.开启分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        // 2.判断是否是带搜索的查询
        if(!StringUtils.isEmpty(queryPageBean.getQueryString())){
            //2.1如果是带搜索的模糊查询，则拼接%
            queryPageBean.setQueryString("%" + queryPageBean.getQueryString() + "%");
        }
        //3.条件查询，这个查询语句会被分页
        Page page = setmealDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询套餐
     */
    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }
    /**
     * 通过id查询选中的检查组ids
     */
    @Override
    public List<Integer> findCheckgroupIdsBySetmealId(int id) {
        return setmealDao.findCheckgroupIdsBySetmealId(id);
    }
    /**
     * 修改套餐
     */
    @Override
    @Transactional
    public void update(Setmeal setmeal, Integer[] checkgroupIds) {
        // 1.先更新套餐信息
        setmealDao.update(setmeal);
        // 2.删除旧关系
        setmealDao.deleteSetmealCheckGroup(setmeal.getId());
        // 3.添加新关系
        if(null != checkgroupIds){
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addSetmealCheckGroup(setmeal.getId(), checkgroupId);
            }
        }
    }

    // 删除套餐
    @Override
    @Transactional
    public void deleteById(Integer id) throws SunnydayException {
        // 1.查看是否存在订单，如果存在则不能删除
        int count = setmealDao.findOrderCountBySetmealId(id);
        if(count > 0){
            // 2.已经有订单使用了这个套餐，不能删除
            throw new SunnydayException("已经有订单使用了这个套餐，不能删除！");
        }
        // 3.先删除套餐与检查组的关系
        setmealDao.deleteSetmealCheckGroup(id);
        // 4.再删除套餐
        setmealDao.deleteById(id);
    }

    @Override
    public List<String> findImgs() {
        return setmealDao.findImgs();
    }

    /**
     * 查询套餐列表
     */
    @Override
    public List<Setmeal> findAll() {
        List<Setmeal> setmealList = setmealDao.findAll();
        //遍历，给集合中的每一个套餐的img属性拼接7牛云的外连接域名
        setmealList.forEach(setmeal -> {
            setmeal.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());
            System.out.println(setmeal.getImg());
        });
        return setmealList;
    }

    @Override
    public Setmeal findDetailById(int id) {
        Setmeal  setmeal=setmealDao.findDetailById(id);
        setmeal.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());
        return setmeal;
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    //---------------------------------------------
    @Autowired
    private FreeMarkerConfig freemarkerConfig;

    @Value("${out_put_path}")
    private String out_put_path;

    /**
     * 封装FreeMark方法
     */
    public void generateHtml(String templateFileName, Map<String,Object> dataMap,String outFileName){
        //1.拿到Configuration对象
        Configuration configuration = freemarkerConfig.getConfiguration();

        //缓冲流,加大读写效率
        BufferedWriter writer= null;
        try {
            //2.加载模板文件-已有
            Template template = configuration.getTemplate(templateFileName);
            //3.准备数据->已有
            //4.输出文件路径
            writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFileName),"utf-8"));
            //5.填充数据
            template.process(dataMap, writer);
            //6.刷流
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //7.关流
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
